const http = require('http')
const path = require('path')
const fs = require('fs')
const mime = require('mime')
const checksum = require('checksum')   // 计算文件的MD5值

const server = http.createServer((req, res) => {
  let filePath = path.resolve(__dirname, path.join('www', req.url))

  if (fs.existsSync(filePath)) {      // 判断文件是否存在
    const stat = fs.statSync(filePath)  // 获取文件信息
    const isDir = stat.isDirectory()   // 判断是否为文件夹s

    if (isDir) {
      filePath = path.join(filePath, 'index.html')  // 如果是文件夹，默认返回index.html
    }

    if (!isDir || fs.existsSync(filePath)) {
      const { ext } = path.parse(filePath)
      const ifNoneMatch = req.headers['if-none-match']

      checksum.file(filePath, (err, sum) => {   // 识别文件资源，资源变更sum变更
        // console.log(sum);  // 6adb05c9d92089507689a7c2beecfc2d814b67eb

        sum = `"${sum}"`
        if (ifNoneMatch === sum) {  // 如果资源没有变，返回304
          res.writeHead(304, {
            'Content-Type': mime.getType(ext),
            'etag': sum
          })
          res.end()
        } else {
          res.writeHead(200, {
            'Content-Type': mime.getType(ext),
            'etag': sum
          })
          const reaStream = fs.createReadStream(filePath)
          reaStream.pipe(res)
        }
      })
    }
  }


})

server.listen(3000)